//
//  MyCollectionViewController.m
//  Findif
//
//  Created by Cicel Chen on 2018/10/25.
//  Copyright © 2018年 Cicel Chen. All rights reserved.
//

#import "MyCollectionViewController.h"
#import "MyCollectionTableViewCell.h"
#import "MyCollectionListModel.h"
#import "ShopDetailsViewController.h"
#import "GoodsDetailsViewController.h"

@interface MyCollectionViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, weak)UIButton * leftButton;
@property (nonatomic, weak)UIButton * rightButton;
@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSArray<MyCollectionListModel *> * myCollectionArray;
@property (nonatomic, assign) BOOL isEditing;//用来标识此时表格视图的状态
@property (nonatomic, weak)UIButton * deleteButton;
//@property (nonatomic, weak)UILabel * showLabel;
@property (nonatomic, weak)UIImageView * spaceImageView;
@property (nonatomic, weak)UILabel * spaceLabel;

@end

@implementation MyCollectionViewController

- (void)setMyCollectionArray:(NSArray<MyCollectionListModel *> *)myCollectionArray{
    
    _myCollectionArray = myCollectionArray;
    
    [self.tableView reloadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = ColorWithRGB(0xF5F5F5);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickCollectionCell:) name:@"clickCollectionCell" object:nil];
    self.isEditing = NO;
    [self setupNav];
    [self loadData];
    [self setupUI];
}


- (void)loadData{
    
    self.myCollectionArray = nil;
    
    [[ZRNetworkTool sharedTool] getUserCollectionListResultWithBlock:^(BOOL success, id responseData) {
        
//        NSLog(@"responseData==%@",responseData);
        if (success) {
            
            self.myCollectionArray = [NSArray yy_modelArrayWithClass:[MyCollectionListModel class] json:responseData[@"data"]];
        }
    }];
}

- (void)setupNav{
    
    self.title = @"我的收藏";
    
    UIButton * leftButton = [[UIButton alloc] init];
    
    leftButton.size = CGSizeMake(40 * SCREENH6, 30 * SCREENH6);
    [leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    leftButton.tag = 1;
    [leftButton addTarget:self action:@selector(didNavButton:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    leftButton.titleLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
    
    self.leftButton = leftButton;
    UIBarButtonItem * leftBar = [[UIBarButtonItem alloc] initWithCustomView:self.leftButton];
    
    self.navigationItem.leftBarButtonItem = leftBar;
    
    
    UIButton * rightButton = [[UIButton alloc] init];
    
    [rightButton setTitle:@"编辑" forState:UIControlStateNormal];
    rightButton.tag = 2;
    [rightButton addTarget:self action:@selector(didNavButton:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    
    self.rightButton = rightButton;
    UIBarButtonItem * rightBar = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    self.navigationItem.rightBarButtonItem = rightBar;
}


- (void)setupUI{
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF5F5F5);
    tableView.rowHeight = 160 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[MyCollectionTableViewCell class] forCellReuseIdentifier:@"MyCollectionTableViewCell"];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self updateData];
    }];
    
    [self.view addSubview:self.tableView];
    
    
    UIButton * deleteButton = [UIButton new];
    
    [deleteButton setTitle:@"删除" forState:UIControlStateNormal];
    [deleteButton setBackgroundColor:ZRBlackColor];
    [deleteButton setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
    [deleteButton addTarget:self action:@selector(clickDeleteButton) forControlEvents:UIControlEventTouchUpInside];
    deleteButton.titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    deleteButton.layer.cornerRadius = 5;
    deleteButton.layer.masksToBounds = YES;
    deleteButton.hidden = YES;
    
    self.deleteButton = deleteButton;
    
    [self.view addSubview:self.deleteButton];
    
    
//    UILabel * showLabel = [UILabel new];
//
//    showLabel.textColor = ZRBlackColor;
//    showLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
//    showLabel.text = @"您还没有收藏商品，快去收藏吧~~";
//    showLabel.textAlignment = NSTextAlignmentCenter;
//    showLabel.hidden = YES;
//
//    self.showLabel = showLabel;
//
//    [self.view addSubview:self.showLabel];
    
    
    UIImageView * spaceImageView = [UIImageView new];
    
    spaceImageView.image = [UIImage imageNamed:@"状态为空"];
    spaceImageView.hidden = YES;
    
    self.spaceImageView = spaceImageView;
    
    [self.tableView addSubview:self.spaceImageView];
    
    
    UILabel * spaceLabel = [UILabel new];
    
    spaceLabel.text = @"您还没有收藏商品，快去收藏吧~~";
    spaceLabel.textColor = [UIColor lightGrayColor];
    spaceLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    spaceLabel.textAlignment = NSTextAlignmentCenter;
    spaceLabel.hidden = YES;
    
    self.spaceLabel = spaceLabel;
    
    [self.tableView addSubview:self.spaceLabel];
}


- (void)viewDidLayoutSubviews{
    
    [self.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.height.mas_equalTo(35 * SCREENH6);
        make.width.mas_equalTo(250 * SCREENH6);
        make.bottom.mas_equalTo(self.view).offset(-20 * SCREENH6);
    }];
    
//    [self.showLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(self.view);
//        make.centerY.mas_equalTo(self.view);
//    }];
    [self.spaceImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.tableView);
        make.centerY.mas_equalTo(self.tableView).offset(-30 * SCREENH6);
        make.width.mas_equalTo(169 * SCREENH6);
        make.height.mas_equalTo(136 * SCREENH6);
    }];
    
    [self.spaceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.spaceImageView);
        make.top.mas_equalTo(self.spaceImageView.mas_bottom).offset(10 * SCREENH6);
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.myCollectionArray.count == 0) {
        
        self.spaceImageView.hidden = NO;
        self.spaceLabel.hidden = NO;
    }else{
        
        self.spaceImageView.hidden = YES;
        self.spaceLabel.hidden = YES;
    }
    return self.myCollectionArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MyCollectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCollectionTableViewCell" forIndexPath:indexPath];
    
        cell.model = self.myCollectionArray[indexPath.row];
        cell.edit = self.isEditing;
//    static NSString * str = @"xxID";
//    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
//    }
//    cell.textLabel.text = [NSString stringWithFormat:@"==%lu",indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.isEditing) {
        
        MyCollectionTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        
        cell.selectButton.selected = !cell.selectButton.selected;
    }
}


- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.isEditing) {
        
        MyCollectionTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        
        cell.selectButton.selected = !cell.selectButton.selected;
    }
}



/**
 *  设置单元格移动样式
 */
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}


- (void)didNavButton:(UIButton *)button{
    
    if (button.tag == 1) {
        
        if (self.isEditing == NO) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            
            self.isEditing = NO;
            self.deleteButton.hidden = YES;
            
            [self.leftButton setTitle:@"" forState:UIControlStateNormal];
            [self.leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
            [self.rightButton setTitle:@"编辑" forState:UIControlStateNormal];
            
            for (MyCollectionTableViewCell *cell in self.tableView.visibleCells) {
                
                cell.selectButton.hidden = YES;
                cell.selectButton.selected = NO;
                cell.edit = NO;
            }
        }
       
    }else{
        
        if (self.isEditing == NO) {
            
            self.isEditing = YES;
            
            self.deleteButton.hidden = NO;
            [self.rightButton setTitle:@"全选" forState:UIControlStateNormal];
            [self.leftButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
            [self.leftButton setTitle:@"取消" forState:UIControlStateNormal];
            
            for (MyCollectionTableViewCell *cell in self.tableView.visibleCells) {

                cell.edit = YES;
            }
        }else{
            for (MyCollectionTableViewCell *cell in self.tableView.visibleCells) {
                
                cell.selectButton.selected = YES;
            }
            
        }
    }
    
    self.tableView.editing = self.isEditing;
}


- (void)clickDeleteButton{
    
    ShowHUD;
    
    NSMutableArray * muArr = [NSMutableArray array];
    
    for (MyCollectionTableViewCell *cell in self.tableView.visibleCells) {
    
        if (cell.selectButton.selected) {
            
            [muArr addObject:cell.goods_id];
        }
    }
    
    NSString * good_id = [muArr componentsJoinedByString:@","];
    
    [[ZRNetworkTool sharedTool] userCancelCollectionGoodsWithGoods_id:good_id ResultWithBlock:^(BOOL success, id responseData) {
        
        HiddenHUD;
        
        if (success) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"恭喜你，删除成功！"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                      [self loadData];
                                                                      self.isEditing = NO;
                                                                      self.deleteButton.hidden = YES;
                                                                      
                                                                      [self.leftButton setTitle:@"" forState:UIControlStateNormal];
                                                                      [self.leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
                                                                      [self.rightButton setTitle:@"编辑" forState:UIControlStateNormal];
                                                                      
                                                                      for (MyCollectionTableViewCell *cell in self.tableView.visibleCells) {
                                                                          
                                                                          cell.selectButton.hidden = YES;
                                                                          cell.selectButton.selected = NO;
                                                                      }
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                    
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}

- (void)clickCollectionCell:(NSNotification *)noti{
    
    NSString * type = noti.userInfo[@"type"];
    NSString * ID = noti.userInfo[@"ID"];
    
    HiddenBar;
    if ([type isEqualToString:@"top"]) {
       
        ShopDetailsViewController * shopVC= [ShopDetailsViewController new];
        shopVC.ID = ID;
        [self.navigationController pushViewController:shopVC animated:YES];
    }else{
        NSString * merchants_goods_type = noti.userInfo[@"merchants_goods_type"];
        GoodsDetailsViewController * goodsVC = [GoodsDetailsViewController new];
        goodsVC.ID = ID;
        goodsVC.infoType = merchants_goods_type;
        [self.navigationController pushViewController:goodsVC animated:YES];
    }
}


- (void)updateData{
    
    [[ZRNetworkTool sharedTool] getUserCollectionListResultWithBlock:^(BOOL success, id responseData) {
        
        //        NSLog(@"responseData==%@",responseData);
        if (success) {
            
            self.myCollectionArray = [NSArray yy_modelArrayWithClass:[MyCollectionListModel class] json:responseData[@"data"]];
        }
    }];
    
    [self.tableView.mj_header endRefreshing];
}

@end
